import { ref } from 'vue'

export interface MessageOptions {
  title?: string
  message: string
  type: 'success' | 'error' | 'warning' | 'info'
  duration?: number
  showClose?: boolean
}

interface MessageInstance {
  id: string
  options: MessageOptions
  visible: boolean
}

const messages = ref<MessageInstance[]>([])
let messageId = 0

export function useMessage() {
  const showMessage = {
    success: (message: string, title?: string, duration = 3000) => {
      addMessage({ message, type: 'success', title, duration })
    },
    error: (message: string, title?: string, duration = 5000) => {
      addMessage({ message, type: 'error', title, duration })
    },
    warning: (message: string, title?: string, duration = 4000) => {
      addMessage({ message, type: 'warning', title, duration })
    },
    info: (message: string, title?: string, duration = 3000) => {
      addMessage({ message, type: 'info', title, duration })
    }
  }

  const addMessage = (options: MessageOptions) => {
    const id = `message_${++messageId}`
    const instance: MessageInstance = {
      id,
      options,
      visible: true
    }

    messages.value.push(instance)

    // 自动关闭
    if (options.duration && options.duration > 0) {
      setTimeout(() => {
        removeMessage(id)
      }, options.duration)
    }

    // 模拟实际的消息提示（在实际项目中，这里会使用UI库的消息组件）
    console.log(`[${options.type.toUpperCase()}] ${options.title || ''} ${options.message}`)
    
    return id
  }

  const removeMessage = (id: string) => {
    const index = messages.value.findIndex(msg => msg.id === id)
    if (index > -1) {
      messages.value.splice(index, 1)
    }
  }

  const clearAll = () => {
    messages.value = []
  }

  return {
    messages,
    showMessage,
    removeMessage,
    clearAll
  }
}